// components/send-bar/send-bar.ts
import { debounce } from "../../utils/index.js";
import dayjs from "dayjs";
import { baseUrl } from "../../utils/service.js";
import { presignedUrl, uploadFile } from "../../utils/api.js";
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        messageData: {
            type: Array,
            value: [],
            observer(newVal) {
                console.log(newVal);
            },
        },
        textareaValue: {
            type: String,
            value: "",
            observer(newVal) {
                console.log(newVal);
            },
        },
        keyboardHeight: {
            type: String,
            value: "",
            observer(newVal) {
                this.setData({ keyboardHeight: newVal });
            },
        },
    },
    created() {
        this.checkRecordPermission();
        // wx.onKeyboardHeightChange((res) => {
        //     console.log("====================================");
        //     console.log(res);
        //     console.log("====================================");
        //     this.setData({
        //         keyboardHeight:
        //             res.height === 0 ? `0px` : `${res.height - 40}px`,
        //     });
        // });
    },
    /**
     * 组件的初始数据
     */
    data: {
        msgDataList: [],
        sendText: true,
        recorderManager: {
            stop: () => {},
        },
        isUserStop: false,
        RecorderManagerOption: {
            duration: 60000,
        },
        recording: false,
        cancel: false,
        imgUrl: "",
        tempMessageId: 0, // 临时消息ID
        isVoicePermission: false,
        keyboardHeight: "",
    },
    /**
     * 组件的方法列表
     */
    methods: {
        /**
         * 当input输入完成，点击完成或者发送按钮执行
         * @param e
         */
        textConfirm(e: any) {
            if (!e.detail.value) return;
            this.triggerEvent("textareaChange", e.detail.value);
        },
        /**
         * 使用防抖
         */
        textChange: debounce(function (e: any) {
            // let value = e[0].detail.value
            // console.log(value);
            // this.triggerEvent('textareaChange', value);
        }, 300),
        textInputFocus() {
            console.log("focus");
            this.triggerEvent("changeInputStatus", 1);
        },
        textInputBlur() {
            console.log("blur");
            this.triggerEvent("changeInputStatus", 0);
        },
        changeSendType(e: baseEvent) {
            const type = e.target.dataset.type;
            this.setData({ sendText: type === "text" });
        },
        /**
         * 处理正在发送中的消息
         */
        loadingMsg(info: any, type: any) {
            const { tempMessageId } = this.data;
            const loginInfo = wx.getStorageSync("userInfo");
            // 生成一个新的临时消息ID
            const newTempMessageId = tempMessageId + 1;
            // 创建一个临时消息项
            if (type == "txt") {
                // 文本消息
                const tempMessage = {
                    id: newTempMessageId,
                    type: type || "txt",
                    sendStatus: "loading", // 设置消息类型为loading
                    msg: info,
                    from: loginInfo.userId,
                    sender: true, // 发送者的userId如果是本地登录用户的id，那么这条消息就是我是发送者
                    avatar:
                        loginInfo.avatar ||
                        "https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg",
                    createTime: dayjs().format("HH:mm:ss"),
                    createDate: dayjs().format("YYYY-MM-DD HH:mm:ss"),
                    showTime: true, // 假设第一条消息默认都要展示时间
                };
                const list: any = [...this.data.msgDataList, tempMessage];
                // 更新消息列表，添加临时消息项
                this.setData(
                    {
                        messageData: JSON.parse(JSON.stringify(list)),
                        tempMessageId: newTempMessageId,
                    },
                    () => {
                        this.triggerEvent(
                            "messageChange",
                            this.data.msgDataList
                        );
                        // 滚动到底部
                        // this.setScrollToBottom();
                    }
                );
            } else {
                const tempMessage = {
                    id: newTempMessageId,
                    type: type || "img",
                    sendStatus: "loading", // 设置消息类型为loading
                    url: info.url,
                    from: loginInfo.userId,
                    sender: true, // 发送者的userId如果是本地登录用户的id，那么这条消息就是我是发送者
                    avatar:
                        loginInfo.avatar ||
                        "https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg",
                    createTime: dayjs().format("HH:mm:ss"),
                    createDate: dayjs().format("YYYY-MM-DD HH:mm:ss"),
                    showTime: true, // 假设第一条消息默认都要展示时间
                };
                const list: any = [...this.data.msgDataList, tempMessage];
                // 更新消息列表，添加临时消息项
                this.setData(
                    {
                        messageData: JSON.parse(JSON.stringify(list)),
                        tempMessageId: newTempMessageId,
                    },
                    () => {
                        // 滚动到底部
                        this.triggerEvent(
                            "messageChange",
                            this.data.messageData
                        );
                        // this.setScrollToBottom();
                    }
                );
            }
        },
        // 移动坐标。判断是否取消
        onTouchMove(e: any) {
            const target = e && e.touches ? e.touches[0] : "";
            if (
                target &&
                target.pageX > 10 &&
                target.pageX < 77 &&
                target.pageY > 630 &&
                target.pageY < 710
            ) {
                if (this.data.cancel) return;
                this.setData({ cancel: true });
            } else {
                if (!this.data.cancel) return;
                this.setData({ cancel: false });
            }
        },
        onTouchstart() {
            const that = this;
            if (!this.data.isVoicePermission) {
                this.getVoicePermission();
                return;
            }
            // 已经有录音权限
            console.log("已经有录音权限");
            that.setData({
                recording: true,
                isUserStop: false,
                cancel: false,
            });
            const recorderManager = wx.getRecorderManager();
            that.data.recorderManager = recorderManager;
            recorderManager.onStart(() => {
                console.log("录音开始");
            });
            recorderManager.onStop((res) => {
                console.log("录音结束");
                if (that.data.isUserStop) {
                    return;
                }
                recorderManager.stop();
                that.setData({ recording: false });
                // 以下是上传图片到我们服务器的代码
                // const fileTypeList = res.tempFilePath.split('.')
                // const fileType = fileTypeList.length > 1 ? `.${fileTypeList[1]}` : '.png'
                const params = {
                    extName: ".aac",
                };
                presignedUrl(params).then((res1) => {
                    const fs = wx.getFileSystemManager();
                    const payload = fs.readFileSync(res["tempFilePath"]);
                    wx.request({
                        url: res1.url,
                        method: "PUT",
                        header: {
                            "content-type": res1.headers["Content-Type"],
                        },
                        data: payload,
                        success: (res2) => {
                            // 注意，此接口比较特殊，res2不会返回图片地址，图片地址是res1里面的url（去掉问号后面一段，只要前面一段，就是图片地址）
                            const picUrlList = res1.url.split("?");
                            let picUrl =
                                picUrlList.length > 0 ? picUrlList[0] : "";
                            const obj = {
                                fileType: "audio",
                                url: picUrl,
                                duration: res.duration,
                            };
                            that.triggerEvent("audioChange", obj);
                        },
                    });
                });
            });
            recorderManager.start(that.data.RecorderManagerOption);
        },
        handleKeyBoardEvent(e: any) {
            if (e.key === "enter") {
                // 这里是按下Enter键后需要执行的代码
                console.log("用户按下了Enter键");
            }
        },
        onTouchend(e: any) {
            this.setData({ recording: false, isUserStop: this.data.cancel });
            this.data.recorderManager.stop();
        },
        checkRecordPermission() {
            const that = this;
            wx.getSetting({
                success(res) {
                    if (!res.authSetting["scope.record"]) {
                        that.data.isVoicePermission = false;
                    } else {
                        that.data.isVoicePermission = true;
                    }
                },
            });
        },
        getVoicePermission() {
            const that = this;
            wx.authorize({
                scope: "scope.record",
                success() {
                    // 用户已同意授权
                    that.data.isVoicePermission = true;
                },
                fail() {
                    // 用户拒绝了授权
                    console.log("用户拒绝了授权");
                    wx.showModal({
                        title: "提示",
                        content:
                            "需要获取录音权限，请点击确定进入设置页面进行授权。",
                        showCancel: true,
                        success(res) {
                            if (res.confirm) {
                                wx.openSetting({
                                    success(res) {
                                        console.log(res.authSetting);
                                        // 用户在设置页面设置了录音权限
                                        if (res.authSetting["scope.record"]) {
                                            console.log(
                                                "用户在设置页面设置了录音权限"
                                            );
                                            that.data.isVoicePermission = true;
                                        } else {
                                            console.log(
                                                "用户在设置页面未设置录音权限"
                                            );
                                            that.data.isVoicePermission = false;
                                        }
                                    },
                                });
                            }
                        },
                    });
                },
            });
        },
        uploadImgAndVideo() {
            const that = this;
            wx.chooseMedia({
                count: 9,
                mediaType: ["image", "video"],
                sourceType: ["album", "camera"],
                maxDuration: 30,
                camera: "back",
                success(res) {
                    if (res.tempFiles[0].fileType == "video") {
                        // 视频
                        that.triggerEvent("imgChange", res);
                    }
                },
            });
        },
        /**
         * 左边的图片的点击按钮（发送图片或者视频）
         */
        openPopup() {
            const that = this;
            wx.chooseMedia({
                count: 9,
                mediaType: ["image", "video"],
                sourceType: ["album", "camera"],
                maxDuration: 30,
                camera: "back",
                success(res) {
                    // 以下是上传图片到我们服务器的代码
                    const fileTypeList =
                        res.tempFiles[0].tempFilePath.split(".");
                    const fileType =
                        fileTypeList.length > 1
                            ? `.${fileTypeList[1]}`
                            : ".png";
                    const msgInfo = {
                        url: res.tempFiles[0].tempFilePath,
                    };
                    // that.loadingMsg(msgInfo ,'img')
                    const params = {
                        extName: fileType,
                    };
                    presignedUrl(params).then((res1) => {
                        const fs = wx.getFileSystemManager();
                        const payload = fs.readFileSync(
                            res.tempFiles[0]["tempFilePath"]
                        );
                        wx.request({
                            url: res1.url,
                            method: "PUT",
                            header: {
                                "content-type": res1.headers["Content-Type"],
                            },
                            data: payload,
                            success: (res2: any) => {
                                // 注意，此接口比较特殊，res2不会返回图片地址，图片地址是res1里面的url（去掉问号后面一段，只要前面一段，就是图片地址）
                                const picUrlList = res1.url.split("?");
                                let picUrl =
                                    picUrlList.length > 0 ? picUrlList[0] : "";
                                that.setData(
                                    {
                                        imgUrl: picUrl,
                                    },
                                    () => {
                                        if (res.type == "video") {
                                            // 视频
                                            const obj = {
                                                fileType: res.type,
                                                url: picUrl,
                                                ...res,
                                            };
                                            that.triggerEvent(
                                                "videoChange",
                                                obj
                                            );
                                            // that.triggerEvent('imgChange', obj);
                                        } else {
                                            const obj = {
                                                fileType: "img",
                                                url: picUrl,
                                            };
                                            that.triggerEvent("imgChange", obj);
                                        }
                                    }
                                );
                            },
                            fail: (error) => {
                                wx.showToast({
                                    title: "上传失败!",
                                    icon: "none",
                                });
                            },
                        });
                    });
                },
            });
        },
    },
});
